# coding=utf-8
from datetime import datetime

from common.order_inquiry.model import *
from common.utils import exceptions as err
from common.utils import track_logging
from common.utils.db import list_object, get, upsert
from common.utils.decorator import sql_wrapper
from common.utils.types import Enum

_LOGGER = track_logging.getLogger(__name__)

INQUIRY_STATUS = Enum({
    "PENDING": (0L, u"待处理"),
    "PROCESSING": (1L, u"处理中"),
    "SUCCESS": (2L, u"成功"),
    "FAILED": (3L, u"失败"),
})


INQUIRY_NOTIFY_STATUS = Enum({
    "READY": (0L, "ready to notify"),
    "FAILED": (1L, "notify failed"),
    "SUCCESS": (2L, "notify successed"),
})


REASON_FAILURE = Enum({
    "INCORRECT_CREDENTIALS": (0L, u"凭证有误请查看示例"),
    "NO_ORDER": (1L, u"查无订单请重新核实"),
    "ORDER_TIMEOUT": (2L, u"订单超时需重新提交"),
    "NOT_RECEIVED_24": (3L, u"红包未领取待24H退回"),
    "NEED_ALIPAY": (4L, u"需提供支付宝红包详情"),
    "START_ERROR_REFILL": (5L, u"发起错误充值订单申诉"),
    "CONTACT_CUSTOMER_SERVICE": (6L, u"特殊情况请咨询客服"),
    "UPLOAD_FAIL": (7L, u"凭证上传失败请重新申诉"),
    "NAME_NOT_MATCH": (8L, u"姓名不符请重新确认"),
    "RE_APPEAL_VOUCHER": (9L, u"请提交同款凭证"),
    "CANNOT_APPEAL": (10L, u"不可申诉"),
    "NO_AMOUNT_RECEIVED": (11L, u"未收到金额请联系客服"),
})


@sql_wrapper
def get_order(id):
    return get(OrderInquiry, id)


@sql_wrapper
def list_order(query_dct):
    return list_object(query_dct, OrderInquiry)


@sql_wrapper
def upsert_order(info, id=None):
    return upsert(OrderInquiry, info, id)


@sql_wrapper
def push_order(id, status):
    try:
        order = get_order(id)
        if order:
            order.notify_status = status
            order.notify_count += 1
            order.notified_at = datetime.utcnow()
            order.save()

    except Exception as e:
        _LOGGER.exception('push_order error, %s', e)
        raise err.DataError()
